package com.example.forwardmessages

import android.content.Context
import android.content.SharedPreferences
import java.text.SimpleDateFormat
import java.util.*

/**
 * Utility class for logging and storing errors persistently
 * with timestamps for error history tracking.
 */
class ErrorLogger(context: Context) {
    private val sharedPreferences: SharedPreferences
    private val errorLogKey = "error_log"
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    private val maxLogEntries = 50 // Limit the number of stored errors

    init {
        sharedPreferences = context.getSharedPreferences("AppErrorLog", Context.MODE_PRIVATE)
    }

    /**
     * Log an error with a message and exception
     */
    fun logError(source: String, message: String, exception: Exception? = null) {
        val timestamp = getCurrentTimestamp()
        val errorDetails = buildErrorDetails(timestamp, source, message, exception)
        
        // Get existing logs
        val existingLogs = getErrorHistory()
        
        // Add new error to the beginning
        val updatedLogs = mutableListOf(errorDetails) + existingLogs
        
        // Keep only the latest entries
        val logsToKeep = updatedLogs.take(maxLogEntries)
        
        // Save back to SharedPreferences
        val editor = sharedPreferences.edit()
        editor.putString(errorLogKey, logsToKeep.joinToString("\n---NEW_ERROR---\n"))
        editor.apply()
    }

    /**
     * Get the complete error history
     */
    fun getErrorHistory(): List<String> {
        val logs = sharedPreferences.getString(errorLogKey, "") ?: ""
        if (logs.isEmpty()) {
            return emptyList()
        }
        return logs.split("\n---NEW_ERROR---\n")
    }

    /**
     * Clear all error logs
     */
    fun clearErrorHistory() {
        val editor = sharedPreferences.edit()
        editor.remove(errorLogKey)
        editor.apply()
    }

    private fun getCurrentTimestamp(): String {
        return dateFormat.format(Date())
    }

    private fun buildErrorDetails(timestamp: String, source: String, message: String, exception: Exception?): String {
        val errorBuilder = StringBuilder()
        errorBuilder.append("[$timestamp] $source: $message")
        
        if (exception != null) {
            errorBuilder.append("\nException: ${exception.javaClass.simpleName}")
            if (exception.message != null) {
                errorBuilder.append(" - ${exception.message}")
            }
            
            // Add stack trace (limited to first 5 lines for brevity)
            val stackTrace = exception.stackTrace.take(5).joinToString("\n")
            errorBuilder.append("\nStack Trace (partial):\n$stackTrace")
        }
        
        return errorBuilder.toString()
    }
}